<template>
  <el-dialog
    title="聚合账单上传"
    :visible.sync="uploadVisible"
    width="950px"
    append-to-body
    @close="closeDialog"
  >
    <el-upload
      ref="uploadCSV"
      action="#"
      accept=".xlsx"
      :on-change="uploadChangeFile"
      :disabled="isUploading"
      :auto-upload="false"
      :show-file-list="false"
      :file-list="fileList"
      drag
      multiple
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>，仅支持CSV格式文件</div>
      <div class="el-upload__tip text-center" slot="tip">
        <div :style="'height: calc(70vh - 230px)'">
          <el-table :data="fileList" >
            <el-table-column label="文件名称" align="left" prop="name" show-overflow-tooltip />
            <el-table-column align="center" width="50">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  :disabled="isUploading"
                  @click="handleDeleteFile(scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="upload-div">
          <el-tag>文件数量：{{ fileList.length }}</el-tag>
        </div>
        <div class="upload-start">
          <el-button
            type="primary"
            @click="handleFileUpload"
            :disabled="uploadDisabled || isUploading"
            :loading="isUploading"
          >
            {{ isUploading ? '上传中...' : '开始上传' }}
          </el-button>
        </div>
      </div>
    </el-upload>
  </el-dialog>
</template>

<script>
import { importCsv } from "@/api/business/payExcels";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      uploadVisible: false,
      fileList: [],
      customColors: [
        { color: "#f56c6c", percentage: 20 },
        { color: "#e6a23c", percentage: 40 },
        { color: "#5cb87a", percentage: 60 },
        { color: "#1989fa", percentage: 80 },
        { color: "#6f7ad3", percentage: 100 },
      ],
      isUploading: false,
    };
  },
  computed: {
    uploadDisabled() {
      return this.fileList.length === 0;
    }
  },
  watch: {
    visible(val) {
      this.uploadVisible = val;
    },
  },
  methods: {
    closeDialog() {
      this.$emit("close");
      this.resetState();
    },

    resetState() {
      this.fileList = [];
      this.isUploading = false;
    },

    uploadChangeFile(file) {
      if (!file || !file.raw || !(file.raw instanceof File)) {
        this.$modal.msgError("无效的文件信息，请重新选择文件。");
        return;
      }

      const validSize = Number(file.size);
      if (isNaN(validSize) || !isFinite(validSize)) {
        this.$modal.msgError("文件大小不合法，请确认后重试。");
        return;
      }

      const isDuplicate = this.fileList.some(item => item.name === file.name);
      if (isDuplicate) {
        this.$modal.msgError("文件已存在，请勿重复添加。");
        return;
      }

      this.fileList.push(file);
    },

    handleDeleteFile(index) {
      this.fileList.splice(index, 1);
    },

    async handleFileUpload() {
      if (this.fileList.length === 0) {
        this.$modal.msgError("请先选择要上传的文件");
        return;
      }

      this.isUploading = true;

      try {
        const formData = new FormData();
        this.fileList.forEach(item => {
          formData.append('files', item.raw);
        });
        formData.append("rulePlatform", "3");
        const response = await importCsv(formData);

        // 成功处理
        this.$modal.msgSuccess(`正在上传${this.fileList.length}个文件`);
        this.closeDialog();
        this.$emit('refreshTable');
      } catch (error) {
        console.error('上传失败:', error);
        this.$modal.msgError(`上传失败: ${error.message || '服务器错误'}`);
      } finally {
        this.isUploading = false;
      }

    },
    getSocketResult(data) {
      if(data.detail.info.code === 200){
        this.$modal.msgSuccess(data.detail.info.msg);
      } else if (data.detail.info.code !== 1000 && data.detail.info.code !== 200){
        this.$modal.msgError(data.detail.info.msg);
      }
      this.$emit('refreshTable');
    },
  },
  mounted() {
    /** websocket接收数据 */
    window.addEventListener('onmessageWS', this.getSocketResult)
  },
};
</script>

<style scoped>
::v-deep .el-upload .el-upload-dragger {
  width: 920px;
  height: 150px;
}
::v-deep .el-dialog__body {
  height: 70vh !important;
}
.upload-div {
  float: left;
  text-align: left;
  display: flex;
  gap: 10px;
  padding-top: 15px;

}
.upload-start {
  float: right;
  padding-top: 10px;
  text-align: right;
}
::v-deep .el-table .warning-row td {
  background: #f56c6c !important;
}
</style>
